package com.hongxun.design.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.hongxun.design.sqlite.bean.Bj;
import com.hongxun.design.sqlite.bean.OldBj;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cqcqwu on 2018/03/29.
 */

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static DatabaseHelper instance;
    private static final String DATABASE_NAME = "ormcl_db";
    private Map<String, Dao> daos;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        this.daos = new HashMap<>();
    }

    //单例获取该Helper
    public static synchronized DatabaseHelper getHelper(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null) instance = new DatabaseHelper(context);
            }
        }
        return instance;
    }

    //单例获取该Dao
    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();
        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }
        if (dao == null) {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        return dao;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            for (Class clazz : getClazz()) {
                TableUtils.createTable(connectionSource, clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Class[] getClazz() {
        return new Class[]{OldBj.class, Bj.class};
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            for (; i < i1; i++) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();
        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }
}
